﻿

#include "utilityBasicFunction.h"

#include "stdio.h"

void rmtree(const char path[]) {
  size_t path_len;
  char *full_path = NULL;
  DIR *dir = NULL;
  struct stat stat_path, stat_entry;
  struct dirent *entry;

  stat(path, &stat_path);

  if (S_ISDIR(stat_path.st_mode) == 0) {
    return;
  }

  if ((dir = opendir(path)) == NULL) {
    return;
  }

  path_len = strlen((char *)path);

  while ((entry = readdir(dir)) != NULL) {
    if (!strcmp(entry->d_name, ".") || !strcmp(entry->d_name, "..")) continue;

    full_path = calloc(path_len + strlen(entry->d_name) + 2, sizeof(char));
    strcpy(full_path, (char *)path);
    strcat(full_path, "/");
    strcat(full_path, entry->d_name);

    stat(full_path, &stat_entry);

    if (S_ISDIR(stat_entry.st_mode) != 0) {
      rmtree(full_path);
      continue;
    }

    if (unlink(full_path) == 0) {
    } else {
      printf("Can`t remove a file: %s\n", full_path);
    }
    free(full_path);
  }

  if (rmdir(path) != 0) printf("Can`t remove a directory: %s\n", path);

  closedir(dir);
}

int remakeDir(const char *path) {
  char oldPath[1024];
  int flag;
  char suffix[] = ".old";

  memcpy(oldPath, (char *)path, strlen((char *)path) + 1);

  memcpy(&oldPath[strlen((char *)path)], suffix, 5);

  if (access(oldPath, F_OK) == 0) {
    rmtree(oldPath);
    flag = access(oldPath, F_OK);
  }
  if (access(path, F_OK) == 0) {
    flag = rename(path, oldPath);
  }
#ifndef _WIN32
  flag = mkdir(path, S_IRWXU);
#else
  flag = mkdir(path);
#endif
  return flag;
}
